package com.tianxin.workbao.workBao.dataProvide;

import android.content.Context;

import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.Coal;
import com.tianxin.workbao.workBao.bean.CoalDao;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.common.URL;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.okhttp.CommonOkHttpClient;
import com.tianxin.workbao.workBao.okhttp.exception.OkHttpException;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataHandle;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataListener;
import com.tianxin.workbao.workBao.okhttp.request.CommonRequest;
import com.tianxin.workbao.workBao.okhttp.request.RequestParams;
import com.tianxin.workbao.workBao.utils.common.BeansUtil;
import com.tianxin.workbao.workBao.utils.common.NetworkUtils;
import com.tianxin.workbao.workBao.utils.common.StringUtils;

import org.greenrobot.greendao.query.Query;
import org.greenrobot.greendao.query.WhereCondition;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hacker on 2017/7/14.
 */

public class CoalProvide extends BaseDataProvide {
    private Integer mPage = 1;
    private List<Coal> mCoals;
    private int isFromServer;
    private UpdateListViewListener mUpdateListViewListener;
    private boolean isGETAll = false;
    private Coal mCoal;
    private CoalDao coalDao;


    public CoalProvide(Context context, UpdateListViewListener listener) {
        super(context);
        mUpdateListViewListener = listener;
        isFromServer = 0;
        coalDao = mGreenDaoHelper.getDaoSession().getCoalDao();
    }

    private void getFromDb(int page) {
        Query<Coal> query = coalDao.queryBuilder().where(CoalDao.Properties.Isis.eq(1))
                .offset((page - 1) * Constant.COAL_PAGE_SIZE)
                .limit(Constant.COAL_PAGE_SIZE)
                .build();
        mCoals = query.list();
    }

    @Override
    public DisposeDataHandle getDisposeDataHandle() {
        disposeDataHandle = new DisposeDataHandle(getDisposeDataListener());
        return disposeDataHandle;
    }

    @Override
    public DisposeDataListener getDisposeDataListener() {
        disposeDataListener = new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                mUpdateListViewListener.hideProgress();
                try {
                    JSONObject object = new JSONObject(responseObj.toString());
                    int status = object.getInt(Constant.RESPONSE_STATUS);
                    String information = object.getString(Constant.RESPONSE_INFO);
                    if (status > 0) {
                        if (mCoals != null && !mCoals.isEmpty()) {
                            mCoals.clear();
                        }
                        String dataJson = object.getString(Constant.RESPONSE_DATA);
                        if (dataJson != null || dataJson.length() > 2) {
                            try {
                                if (dataJson.startsWith("[") && dataJson.endsWith("]") && dataJson.length() > 3) {
                                    if (mCoals != null && !mCoals.isEmpty()) {
                                        mCoals.clear();
                                    }
                                    mCoals = BeansUtil.coalToBeans(dataJson);
                                    refreshUI();
                                    saveToDb(mCoals);
                                } else {
                                    mCoal = BeansUtil.coalToBean(dataJson);
                                    saveToDb(mCoal);
                                }
                            } catch (Exception e) {
                                mUpdateListViewListener.showMessage("coal To Bean Error :类型转换出错" + e.getMessage());
                            }

                        } else {
                            mUpdateListViewListener.showMessage(information);
                        }
                    } else {
                        mUpdateListViewListener.showMessage(information);
                    }
                } catch (JSONException e) {
                    showRequestErrorMessage(mUpdateListViewListener, responseObj.toString());
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Object reasonObj) {
                mUpdateListViewListener.hideProgress();
                if (reasonObj instanceof OkHttpException) {
                    OkHttpException exception = (OkHttpException) reasonObj;
                    mUpdateListViewListener.showMessage(exception.getEcode() + ":" + exception.getEmsg().toString());
                } else {
                    showRequestErrorMessage(mUpdateListViewListener, reasonObj.toString());
                }
            }
        };
        return disposeDataListener;
    }

    /**
     * true save data to databases
     *
     * @param obj
     */
    private void saveToDb(Object obj) {
        CoalDao coalDao = mGreenDaoHelper.getDaoSession().getCoalDao();
        if (obj instanceof List) {
            for (int i = 0; i < mCoals.size(); i++) {
                coalDao.insertOrReplace(mCoals.get(i));
            }
        } else {
            coalDao.insertOrReplace((Coal) obj);
        }
    }

    /**
     * get coals 获取煤种列表
     *
     * @param page
     */
    public void getCoals(int page) {
        mPage = page;
        if (NetworkUtils.isConnected(mContext)) {
            getFromServer();
        } else {
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
            getFromDb(mPage);
            refreshUI();
        }

    }

    /**
     * update the coal data  from server
     */
    private void getFromServer() {
        mUpdateListViewListener.showProgress();
        isFromServer = 1;
        Map<String, String> map = new HashMap<>();
        map.put(Constant.APPTOKEN_NAME, getAppToken());
        map.put("page", mPage + "");
        RequestParams params = new RequestParams(map);
        CommonOkHttpClient.post(CommonRequest.createPostRequest(URL.getCoalsUrl(), params), getDisposeDataHandle());
    }

    @Override
    public void refreshUI() {
        if (mCoals != null && !mCoals.isEmpty()) {
            if (mPage > 1) {
                mUpdateListViewListener.onLoadMoreData(mCoals);
            } else {
                mUpdateListViewListener.onRefreshData(mCoals);
            }
        }
    }

    /**
     * get all coal in the user
     */
    public void getAllCoals() {
        isGETAll = true;
        if (NetworkUtils.isConnected(mContext)) {
            mUpdateListViewListener.showProgress();
            isFromServer = 1;
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            RequestParams params = new RequestParams(map);
            CommonOkHttpClient.post(CommonRequest.createPostRequest(URL.getCoalsUrl(), params), getDisposeDataHandle());
        } else {
            mUpdateListViewListener.showMessage(
                    mContext.getResources().getString(R.string.poor_network));
        }
    }

    public void search(String query) {
        if (mCoals != null) {
            mCoals.clear();
            mPage = 1;
        }
        String where = "";
        if (StringUtils.isHasChineseChar(query)) {
            where = "typename like '%" + query + "%'";
        } else if (StringUtils.isLatter(query)) {
            where = "clabbreviation like '%" + query + "%'";
        } else {
            mUpdateListViewListener.showMessage("输入有错！");
        }
        if (where.length() < 1) return;
        Query<Coal> userQuery = coalDao.queryBuilder()
                .where(new WhereCondition.StringCondition(where))
                .orderAsc(CoalDao.Properties.Typename)
                .build();
        mCoals = userQuery.list();
        refreshUI();
    }
}
